const express = require('express')
const router = express.Router()
const categoryAction = require('../Controller/categorys')
const xss = require('node-xss').clean;
const check = require('../mid') //检查中间件


// 分类页面
router.get('/category-admin:id',check.isLogin, function (req, res) {
    let id = req.params.id
    categoryAction.getByid(id, function (allcate, curentcate, arctile) {
        if (allcate && curentcate) {
            res.render('categorys-admin.html', { allcate, curentcate })
        }
    })
})

// 新增分类
router.post('/addCategory',check.isLogin,check.isPower1,function (req, res) {
    let cate=xss(req.body)
    categoryAction.add(cate, function (doc) {
        if(doc){
            req.flash('msg')
            req.flash('msg','分类添加成功')
            res.redirect('/admin/jump')
        } 
    })
})



//修改分类
router.post('/editCategory:id',check.isLogin,check.isPower1,function (req, res) {
    let id = req.params.id
    let cate =xss(req.body)
  
    categoryAction.updateByid(id, cate, function (doc) {
        if(doc){
            req.flash('msg')
            req.flash('msg','分类修改成功')
            res.redirect('/admin/jump')
        }
    })
})

//删除分类
router.get('/deleteCategory:id',check.isLogin,check.isPower1, function (req, res) { 
    let id = req.params.id;
    categoryAction.deleteByid(id, function (doc) {
        if(doc){
            req.flash('msg')
            req.flash('msg','分删除成功')
            res.redirect('/admin/jump')
        }
    })
})

//异步请求分类api
router.get('/getCategory', function (req, res) {
    categoryAction.all(function (doc) {
        res.json(doc)
    })
})

//异步请求分类文章api
router.get('/getCategoryArt:id', function (req, res) {
    let id = req.params.id
    categoryAction.allActile(id, function (doc) {
        res.json(doc)
    })
})

module.exports = router